package com.example.gulimallauthserver.util;

import com.alibaba.fastjson.JSON;
import com.example.gulimallauthserver.vo.GiteeToken;
import com.example.gulimallauthserver.vo.GiteeUserVo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


public class GiteeUtil {
    public static final String ClientID = "84ced7c3a745b8b875b28f218da6eceb026f458874251bd684e6c3bbfb2b05f0";
    public static final String ClientSecret = "9a4713b378730a8e0161d8bab3d99228b099e2207f6b06caf4dfe997b15aa74e";
    public static final String RedirectUri = "http://auth.gulimall.com/gitee/auth"; //回调地址
    //    public static final String RedirectUri = "https://2dbfb5d2.r7.cpolar.top/gitee/auth"; //回调地址
    public static CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    /**
     * 拼接 URL
     * @return url
     * @throws UnsupportedEncodingException Exception
     */
    public static String getUrl() throws UnsupportedEncodingException {
        String url = URLEncoder.encode(RedirectUri, "UTF-8");
        return "https://gitee.com/oauth/authorize?client_id=" + ClientID + "&redirect_uri=" + url + "&response_type=code";
    }

    /**
     * 发起请求获取Token
     * @param code 校验码
     * @return 返回数据
     * @throws Exception exception
     */
    public static GiteeToken getToken(String code) throws Exception {
        //新建httpClient对象 新建post请求对象
        HttpPost postRequest = new HttpPost("https://gitee.com/oauth/token");

        //post请求对象传入值
        StringEntity input = new StringEntity(
                "grant_type=authorization_code&" +
                        "code=" + code +
                        "&client_id=" + ClientID +
                        "&redirect_uri=" + RedirectUri +
                        "&client_secret=" + ClientSecret);

        input.setContentType("application/x-www-form-urlencoded");
        postRequest.setEntity(input);

        //httpClient执行 post请求 并获取返回内容·
        HttpResponse response = httpClient.execute(postRequest);
        HttpEntity entity = response.getEntity();
        String jsonStr = EntityUtils.toString(entity);
        System.out.println("JSONSTR: "+jsonStr);
        //控制台
        GiteeToken gt = JSON.parseObject(jsonStr,GiteeToken.class);

        return gt;
    }

    /**
     * 刷新 Gitee 的 token
     * @param refreshToken 先前获取到的refreshToken
     * @return 返回新的 GiteeToken 对象
     * @throws IOException exception
     */
    public static GiteeToken RefreshToken(String refreshToken) throws IOException {
        HttpPost postRequest = new HttpPost("https://gitee.com/oauth/token");

        StringEntity input = new StringEntity("grant_type=refresh_token&refresh_token=" + refreshToken);
        input.setContentType("application/x-www-form-urlencoded");

        //数据传入方法体
        postRequest.setEntity(input);

        //执行请求
        HttpResponse response = httpClient.execute(postRequest);
        HttpEntity entity = response.getEntity();
        String jsonStr = EntityUtils.toString(entity);

        System.out.println(jsonStr);

        //将JSON数据实例化为GiteeToken对象
        return JSON.parseObject(jsonStr, GiteeToken.class);
    }

    /**
     * 根据用户的token获取用户的信息
     * @param token access_token
     * @return W
     * @throws IOException exception
     */
    public static GiteeUserVo getInfo(String token) throws IOException {

        //配置
        HttpGet emailGet = new HttpGet("https://gitee.com/api/v5/emails?access_token="+token);
        HttpGet userGet = new HttpGet("https://gitee.com/api/v5/user?access_token="+token);

        //执行请求获取内容
        HttpEntity entity1 = httpClient.execute(emailGet).getEntity();
        HttpEntity entity2 = httpClient.execute(userGet).getEntity();

        //获取邮箱
        String jsonStr4email = EntityUtils.toString(entity1);
        String substring = jsonStr4email.substring(1, jsonStr4email.length()-1);
        String email = JSON.parseObject(substring).getString("email");

        //获取用户
        String jsonStr4User = EntityUtils.toString(entity2);
        GiteeUserVo giteeUser = JSON.parseObject(jsonStr4User, GiteeUserVo.class);
        giteeUser.setEmail(email);//将邮箱信息添加至用户

        return giteeUser;
    }
}
